package org.nfIt.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.nfIt.utils.JwtUtil;
import org.nfIt.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * ClossName:LoginInterceptors
 * Pakage:org.nfIt.interceptors
 * Description
 *
 * 全局拦截器,需要注册 WebConfig
 *
 * @Author L
 * @Create 2024/6/4 17:40
 * @Version 2023.1.3
 */
@Component
public class LoginInterceptors implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     *前处理
     * @param request 请求域
     * @param response 响应域
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求域中获取token
        String token = request.getHeader("Authorization");
        try {

            //从浏览器中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken == null){
                //token失效
                throw new RuntimeException("token 失效了");

            }

            //验证token
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把解析好的数据,存入ThreadLocalUtil 线程中
            ThreadLocalUtil.set(claims);
           // System.out.println(claims);//{id=4, username=shenyyy}

            //放行
            return true;
        }catch (Exception e){
            //设置http响应状态码
            response.setStatus(401);
            //不放行
            return false;
        }
    }

    /**
     * 后处理
     * 响应完成后,清空thread线程的内存
     * @param request 请求域
     * @param response 响应域
     * @param handler
     * @param ex 异常
     * @throws Exception 抛出异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //响应完成后,清空thread线程的内存
        ThreadLocalUtil.remove();
    }
}
